<template>
  <div>
    <div class="dialog_header">
      <div class="top_wrap">
        <el-select
          v-model="dateStatus"
          placeholder="请选择"
          style="width: 174px"
          @change="changeDateStatus"
        >
          <el-option
            v-for="item in dateStatusOptions"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          ></el-option>
        </el-select>
        <div class="template_list">
          <template v-for="(item, index) in templateList" :key="item.id">
            <div
              :class="['template_item', { active: templateIndex == index }]"
              @click="changeTemplate(item, index)"
            >
              <p>{{ item.templateName }}</p>
              <p class="temp_label" v-if="item.isDefault == 0">默认</p>
            </div>
          </template>
          <div class="add_box" @click="addTemplate">
            <img src="@/assets/images/icon/handle_add.png" alt="" />
          </div>
        </div>
      </div>
    </div>
    <div style="height: 640px" v-loading="siteLoading">
      <div
        style="padding-top: 18px; padding-bottom: 100px"
        v-if="templateList != null && templateList.length > 0"
      >
        <table>
          <thead>
            <tr>
              <th rowspan="2">时段</th>
              <th v-for="venue in halfList" :key="venue.id" :rowspan="venue.id">
                {{ venue.siteName }}
              </th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="(item, index) in workTime" :key="index">
              <td style="text-align: center">
                <div class="flex items-center justify-center">
                  <img :src="getTimeIcon(item.disabled)" alt="" />
                  <span
                    :class="['mx-4', item.disabled ? 'text-custom-grey' : 'text-custom-main']"
                    >{{ item.time }}</span
                  >
                  <p
                    :class="[
                      'text-xs',
                      'text-blue',
                      'w-16',
                      'text-left',
                      item.disabled ? 'text-custom-grey' : 'text-custom-blue',
                    ]"
                    style="cursor: pointer"
                    @click="handleDisabledTime(item)"
                  >
                    {{ item.disabled ? '取消' : '' }}禁用
                  </p>
                </div>
              </td>
              <td
                v-for="venue in halfList"
                :key="venue.id"
                :class="{
                  disabled_price:
                    item.disabled || reservations[venue.id]?.[item.time]?.orderType == 2,
                }"
              >
                <div class="flex justify-center items-center">
                  <div
                    v-if="reservations[venue.id] && reservations[venue.id]?.[item.time]"
                    style="text-align: center"
                  >
                    <span
                      style="color: #a6a6a6"
                      v-if="item.disabled || reservations[venue.id]?.[item.time]?.orderType == 2"
                    >
                      {{ reservations[venue.id]?.[item.time]?.price || '请选择价格'
                      }}<i class="el-icon-arrow-down el-icon--right"></i>
                    </span>
                    <!---这里禁用下拉框的条件为：已过当前时间，或是已被预定（小程序或者pc操作订场都会禁用）---->
                    <el-dropdown
                      style="text-align: center"
                      @command="selectMoney($event, item.time, venue.id)"
                      v-else
                    >
                      <span
                        class="el-dropdown-link"
                        :style="{
                          color:
                            reservations[venue.id]?.[item.time]?.price !== null
                              ? '#000'
                              : '#a6a6a6',
                        }"
                      >
                        {{ reservations[venue.id]?.[item.time]?.price || '请选择价格'
                        }}<i class="el-icon-arrow-down el-icon--right"></i
                      ></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <template v-for="command in uPriceList" :key="command.price">
                            <el-dropdown-item
                              :command="command.price"
                              v-if="command.id === venue.id || command.id == ''"
                            >
                              {{ command.price }}
                            </el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <div v-else style="text-align: center">
                    <el-dropdown
                      @command="selectMoney($event, item.time, venue.id)"
                      style="text-align: center"
                    >
                      <span class="el-dropdown-link" style="color: #a6a6a6">
                        请选择价格<i class="el-icon-arrow-down el-icon--right"></i
                      ></span>
                      <template #dropdown>
                        <el-dropdown-menu>
                          <template v-for="command in priceList" :key="command.price">
                            <el-dropdown-item
                              :command="command.price"
                              v-if="command.id === venue.id"
                            >
                              {{ command.price }}
                            </el-dropdown-item>
                          </template>
                        </el-dropdown-menu>
                      </template>
                    </el-dropdown>
                  </div>
                  <p
                    :class="[
                      'text-xs',
                      'text-blue',
                      'text-left',
                      'ml-3',
                      'w-16',
                      'leading-5',
                      reservations[venue.id]?.[item.time]?.orderType == 2
                        ? 'text-custom-grey'
                        : 'text-custom-blue',
                    ]"
                    style="cursor: pointer"
                    v-if="!item.disabled"
                    @click="
                      handleDisBulletin(
                        reservations[venue.id]?.[item.time]?.orderType,
                        item.time,
                        venue.id,
                      )
                    "
                  >
                    {{ reservations[venue.id]?.[item.time]?.orderType == 2 ? '取消' : '' }}禁用
                  </p>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
        <div class="temp_btn">
          <el-button type="primary" @click="handleSubmit()">保存</el-button>
          <el-button type="primary" @click="handleDefault">设为默认</el-button>
          <el-button @click="handleCancel">取消</el-button>
          <el-button @click="handleDelTemp">删除</el-button>
        </div>
      </div>
      <div class="not_set" v-if="templateList != null && templateList.length == 0">
        <img src="@/assets/images/icon/not_cont.png" alt="" />
        <div>
          <p class="p1">尚未设置价格模版</p>
          <p class="p2" @click="addTemplate">去设置》</p>
        </div>
      </div>
    </div>

    <!-- 添加模版 -->
    <el-dialog
      title="添加模版"
      v-model="addTempVisible"
      width="500px"
      append-to-body
      :close-on-click-modal="false"
      custom-class="add_temp"
    >
      <el-form
        ref="tempFormRef"
        :model="tempForm"
        :rules="rules"
        label-width="84px"
        @submit.prevent
      >
        <el-form-item label="模版名称" prop="name">
          <el-input
            placeholder="请输入"
            v-model="tempForm.name"
            @keyup.enter="submitTemp"
          ></el-input>
        </el-form-item>
      </el-form>
      <div class="dialog_btn">
        <el-button @click="addTempVisible = false">取消</el-button>
        <el-button type="primary" @click="submitTemp">确定</el-button>
      </div>
    </el-dialog>
    <!-- 保存模版提示 -->
    <el-dialog
      v-model="saveTipsVisible"
      width="417px"
      append-to-body
      :close-on-click-modal="false"
      :modal="false"
      :show-close="false"
      custom-class="add_temp save_tips"
    >
      <div>
        <div class="dialog_top">
          <img src="@/assets/images/icon/warn_icon.png" />
          <span>是否保存当前模板？</span>
        </div>
        <div class="tips_cont">当前数据未保存，是否离开？</div>
        <div class="dialog_btn">
          <el-button type="primary" @click="handleSubmit(1)">保存</el-button>
          <el-button @click="handleNotSave">不保存</el-button>
          <el-button @click="saveTipsVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
    <!-- 保存模版提示 -->
    <el-dialog
      v-model="saveDefaultVisible"
      width="417px"
      append-to-body
      :close-on-click-modal="false"
      :modal="false"
      :show-close="false"
      custom-class="add_temp save_tips"
    >
      <div>
        <div class="dialog_top">
          <img src="@/assets/images/icon/warn_icon.png" />
          <span>是否将当前模板设为默认？</span>
        </div>
        <div class="tips_cont">选择确认将保存当前模板并设为默认</div>
        <div class="dialog_btn">
          <el-button type="primary" @click="handleSubmit(1)">确认</el-button>
          <el-button @click="saveDefaultVisible = false">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, nextTick, type Ref } from 'vue'
import { debounce } from 'lodash'
import {
  getBusinessTimeById,
  getPriceListByIdAndType,
  saveBulletin,
  getBulletinListBySite,
  getSiteListToTemplate,
} from '@/api/site/site'
import { getTemplateList, deleteTemplate, createBulletinTemplate } from '@/api/stadium/stadium'
import dayjs from 'dayjs'
import type { FormInstance } from 'element-plus'

// 定义组件名称
defineOptions({
  name: 'SessionDetail',
})

// 定义 emits
const emit = defineEmits<{
  (e: 'cancel'): void
  (e: 'success'): void
}>()

// 类型定义
interface SiteItem {
  id: string
  siteName: string
  enable: string
  [key: string]: any
}

interface WorkTimeItem {
  time: string
  disabled: boolean
}

interface BusinessTime {
  workDateStart: string | null
  workDateEnd: string | null
  legalDateStart: string | null
  legalDateEnd: string | null
}

interface PriceItem {
  id: string
  price: string
  [key: string]: any
}

interface TemplateItem {
  id: string | null
  templateName: string
  isDefault: number
  templateType: string
  displayTimes?: string
  isInput?: boolean
}

interface ReservationItem {
  price: string | null
  orderType: number | string | null
}

interface ReservationData {
  [siteId: string]: {
    [time: string]: ReservationItem
  }
}

interface PriceDataItem {
  siteId: string
  time: string
  price: string | null
  stadiumId: string
  orderType?: number | string | null
}

// 获取时间图标
const getTimeIcon = (disabled: boolean) => {
  return new URL(
    `../assets/images/icon/${disabled ? 'time_dis' : 'time_notdis'}.png`,
    import.meta.url,
  ).href
}

// 响应式数据
const enabledBoard = ref(true)
const selectDate = ref('')
const halfList = ref<SiteItem[]>([])
const workTime = ref<WorkTimeItem[]>([])
const dateList = ref<any[]>([])
const activeTab = ref('1')
const reservations = ref<ReservationData>({})
const businessTime = reactive<BusinessTime>({
  workDateStart: null,
  workDateEnd: null,
  legalDateStart: null,
  legalDateEnd: null,
})
const clickDay = ref('')
const peopleNumber = ref('')
const residueNumber = ref('')
const priceList = ref<PriceItem[]>([])
const uPriceList = ref<PriceItem[]>([])
const siteType = ref('')
const siteData = ref<any>({})
const siteIdsString = ref('')
const isToday = ref(true)
const siteLoading = ref(false)
const priceDatas = ref<PriceDataItem[]>([])
const dataLoaded = ref(false)
const templateList = ref<TemplateItem[] | null>(null)
const dateStatusOptions = ref([
  { id: '0', name: '工作日' },
  { id: '1', name: '节假日' },
])
const dateStatus = ref('0')
const templateIndex = ref(0)
const templateId = ref<string | null>(null)
const templateName = ref('')
const addTempVisible = ref(false)
const tempForm = reactive({
  name: '',
})
const rules = ref({
  name: [
    {
      required: true,
      message: '请输入模版名称',
      trigger: 'blur',
    },
  ],
})
const isEditPrice = ref(false)
const saveTipsVisible = ref(false)
const isLoading = ref(false)
const templateParams = ref<{
  templateId: string | null
  templateIndex: number
  templateName: string
}>({
  templateId: null,
  templateIndex: 0,
  templateName: '',
})
const handleStatus = ref('')
const disabledTimes = ref<string[]>([])
const isDefault = ref(false)
const saveDefaultVisible = ref(false)

// refs
const tempFormRef = ref<FormInstance>()

// 方法定义
const open = async (row: any) => {
  templateList.value = []
  resetForm()
  siteLoading.value = true
  //暂存父级数据
  siteData.value = row
  //获取场地集合
  halfList.value = siteData.value?.children?.filter((item: SiteItem) => item.enable == '1') || []
  //场馆id
  const stadiumId = row.stadiumId
  //场地类型
  siteType.value = row.type
  const siteIds = halfList.value?.map((item: SiteItem) => item.id)
  siteIdsString.value = siteIds.join(',')
  getPriceList(siteIdsString.value)
  await getTemplate(stadiumId, siteType.value)
  templateIndex.value = 0
  // 使用局部变量帮助TypeScript正确进行类型缩小
  const currentTemplateList = templateList.value
  if (currentTemplateList !== null && currentTemplateList.length > 0) {
    templateId.value = currentTemplateList[0]?.id || null
    templateName.value = currentTemplateList[0]?.templateName || ''
    dateStatus.value = currentTemplateList[0]?.templateType || '0'
    disabledTimes.value = currentTemplateList[0]?.displayTimes?.split(',') || []
    isDefault.value = currentTemplateList[0]?.isDefault === 0 ? true : false
  }
  await getBusinessTime(stadiumId)
  await getReserveList(stadiumId, siteIdsString.value)
}

const getSite = async (stadiumId: string, siteType: string) => {
  const { data } = await getSiteListToTemplate({
    stadiumId: stadiumId,
    type: siteType,
  })
  halfList.value = data
  const siteIds = halfList.value?.map((item: SiteItem) => item.id)
  siteIdsString.value = siteIds.join(',')
  getPriceList(siteIdsString.value)
}

//初始化页面元素
const resetForm = () => {
  siteData.value = {}
  halfList.value = []
  selectDate.value = ''
  clickDay.value = ''
  isToday.value = true
  peopleNumber.value = ''
}

// 获取价格模版列表
const getTemplate = async (stadiumId: string, siteType: string) => {
  try {
    const { data } = await getTemplateList({
      stadiumId: stadiumId,
      siteType: siteType,
    })
    templateList.value = data
    if (templateList.value !== null) {
      templateList.value.forEach((item) => {
        item.isInput = false
      })
    }
  } catch (e) {
    siteLoading.value = false
  }
}

//根据场馆id查询场馆营业时间
const getBusinessTime = (stadiumId: string) => {
  getBusinessTimeById({ id: stadiumId }).then((response) => {
    if (response.code == 200) {
      Object.assign(businessTime, response.data)
      if (undefined != businessTime && undefined != businessTime.workDateStart) {
        let timeStrings: string[] = []
        if (dateStatus.value == '0') {
          timeStrings = generateHourlyTimesInFormat(
            businessTime.workDateStart,
            businessTime.workDateEnd,
          )
        } else {
          timeStrings = generateHourlyTimesInFormat(
            businessTime.legalDateStart,
            businessTime.legalDateEnd,
          )
        }
        workTime.value = timeStrings.map((time) => ({
          time,
          disabled: false,
        }))
        workTime.value.forEach((item) => {
          disabledTimes.value.forEach((ele) => {
            if (item.time == ele) {
              item.disabled = true
            }
          })
        })
      } else {
        workTime.value = []
      }
    } else {
      workTime.value = []
    }
  })
}

//根据开始以及结束时间获取中间小时列表
const generateHourlyTimesInFormat = (
  startTimeStr: string | null,
  endTimeStr: string | null,
): string[] => {
  if (!startTimeStr || !endTimeStr) return []

  const timeRanges: string[] = []
  const startParts = startTimeStr.split(':')
  const endParts = endTimeStr.split(':')

  if (startParts.length < 1 || endParts.length < 1) return []

  // 确保至少有一个部分并且可以正确解析为数字
  const startHourStr = startParts[0] ?? ''
  const endHourStr = endParts[0] ?? ''

  const startHour = parseInt(startHourStr, 10)
  const endHour = parseInt(endHourStr, 10)

  // 检查是否成功解析为有效数字
  if (isNaN(startHour) || isNaN(endHour)) return []

  for (let hour = startHour; hour < endHour; hour++) {
    // 格式化小时数，确保始终是两位数
    const start = hour.toString().padStart(2, '0') + ':00'
    const end = (hour + 1).toString().padStart(2, '0') + ':00'
    // 创建时间范围字符串并添加到数组中
    timeRanges.push(`${start} - ${end}`)
  }
  // 添加最后一个时间范围，确保它不重复
  const lastStart = endHour.toString().padStart(2, '0') + ':00'
  const lastEnd = lastStart // 如果是最后一个小时，开始和结束时间相同
  if (lastEnd != lastStart) {
    timeRanges.push(`${lastStart} - ${lastEnd}`)
  }
  return timeRanges
}

//近七日日期获取
const getDaysDates = () => {
  const dates = []
  const today = new Date()
  const dayNames = ['今天', '明天', '后天']

  for (let i = 0; i < 7; i++) {
    const date = new Date(today)
    date.setDate(today.getDate() + i)

    const dateString = date.toLocaleDateString('zh-CN', {
      month: '2-digit',
      day: '2-digit',
    })
    const dayName = i < 3 ? dayNames[i] : dateString

    dates.push({
      day: dayName,
      date: dateString,
    })
    dateList.value = dates
  }
}

//选择价格
const selectMoney = (command: string, row: string, siteId: string) => {
  isEditPrice.value = true
  let foundMatch = false
  priceDatas.value.forEach((item) => {
    if (item.siteId == siteId && item.time == row) {
      item.price = command
      foundMatch = true
    }
  })
  if (!foundMatch) {
    priceDatas.value.push({
      siteId,
      time: row,
      price: command,
      stadiumId: siteData.value.stadiumId,
    })
  }
  convertListToReservations(priceDatas.value)
}

// 禁用场次
const handleDisBulletin = (
  val: number | string | undefined | null,
  row: string,
  siteId: string,
) => {
  isEditPrice.value = true
  let foundMatch = false
  let orderType = null
  if (val == 2) {
    orderType = null
  } else {
    orderType = 2
  }
  priceDatas.value.forEach((item) => {
    if (item.siteId == siteId && item.time == row) {
      item.orderType = orderType
      foundMatch = true
    }
  })
  if (!foundMatch) {
    priceDatas.value.push({
      siteId,
      time: row,
      price: null,
      stadiumId: siteData.value.stadiumId,
      orderType,
    })
  }
  convertListToReservations(priceDatas.value)
}

//保存信息
const save = (time: string, price: string, siteId: string, stadiumId: string) => {
  let days
  if (clickDay.value == '' && selectDate.value == '') {
    days = new Date().getFullYear() + '/' + (dateList.value[0] as any)?.date
  } else if (clickDay.value != '') {
    days = new Date().getFullYear() + '/' + clickDay.value
  } else {
    days = dayjs(selectDate.value).format('YYYY/MM/DD')
  }

  const params = {
    stadiumId: stadiumId,
    siteId: siteId,
    date: days,
    time: time,
    price: price,
    peopleNumber: peopleNumber.value,
    orderType: '',
  }
  saveBulletin(params).then((response) => {
    if (response.code == 200) {
      // 使用 Element Plus 的消息提示
      // this.$message({
      //   type: "success",
      //   message: "操作成功！",
      // })
      getReserveList(stadiumId, siteIdsString.value)
      emit('success')
    }
  })
}

//获取价格列表
const getPriceList = (ids: string) => {
  priceList.value = []
  uPriceList.value = []
  const params = {
    id: ids,
  }
  getPriceListByIdAndType(params).then((response) => {
    if (response.code == 200) {
      if (response.data.length > 0) {
        priceList.value = response.data
        uPriceList.value = priceList.value
      } else {
        const data = {
          price: '0.00',
        }
        priceList.value.push(data as any)
      }
    }
  })
}

//已设定场次列表查询
const getReserveList = (stadiumId: string, siteIdsString: string) => {
  siteLoading.value = true
  const params: any = {
    stadiumId: stadiumId,
    siteIds: siteIdsString.split(','),
  }
  let days
  if (clickDay.value == '' && selectDate.value == '') {
    days = new Date().getFullYear() + '/' + (dateList.value[0] as any)?.date
  } else if (clickDay.value != '') {
    days = new Date().getFullYear() + '/' + clickDay.value
  } else {
    days = dayjs(selectDate.value).format('YYYY/MM/DD')
  }
  params.date = days
  getBulletinListBySite({ templateId: templateId.value })
    .then((response) => {
      if (response.code == 200) {
        siteLoading.value = false
        priceDatas.value = response.data
        convertListToReservations(priceDatas.value)
      }
    })
    .catch(() => {
      siteLoading.value = false
    })
}

//处理数据用于回显已设定价格
const convertListToReservations = (list: PriceDataItem[]) => {
  const reservationsData: ReservationData = {}

  list.forEach((item) => {
    const siteName = item.siteId //siteId
    const timeSlot = item.time // 时间段

    // 初始化场地名称对应的对象
    if (!reservationsData[siteName]) {
      reservationsData[siteName] = {}
    }

    // 将预订信息添加到对应的场地和时间段
    if (item.orderType == undefined || item.orderType == '') {
      reservationsData[siteName][timeSlot] = {
        price: item.price,
        orderType: item.orderType || null,
      }
    } else {
      reservationsData[siteName][timeSlot] = {
        price: item.price,
        orderType: item.orderType,
      }
    }
  })
  reservations.value = reservationsData
}

// 确认添加模版
const submitTemp = () => {
  if (!tempFormRef.value) return
  tempFormRef.value.validate(async (valid) => {
    if (valid) {
      if (!templateList.value) templateList.value = []
      templateList.value.push({
        id: null,
        templateName: tempForm.name,
        isInput: true,
        isDefault: 0,
        templateType: '0',
      } as TemplateItem)
      addTempVisible.value = false
      templateIndex.value = templateList.value.length - 1
      templateId.value = null
      dateStatus.value = '0'
      templateName.value = tempForm.name
      disabledTimes.value = []
      isDefault.value = false
      // 重新获取营业时间
      if (siteData.value.stadiumId) {
        getBusinessTime(siteData.value.stadiumId)
      }
      priceDatas.value = []
      convertListToReservations(priceDatas.value)
    }
  })
}

// 选择模版
const changeTemplate = (item: TemplateItem, index: number) => {
  handleStatus.value = 'change'
  templateParams.value = {
    templateId: item.id,
    templateIndex: index,
    templateName: item.templateName,
  }
  if (isEditPrice.value) {
    saveTipsVisible.value = true
    return
  }
  templateId.value = item.id
  templateIndex.value = index
  templateName.value = item.templateName
  dateStatus.value = item.templateType || '0'
  disabledTimes.value = item.displayTimes?.split(',') || []
  isDefault.value = item.isDefault == 0 ? true : false
  if (siteData.value.stadiumId) {
    getBusinessTime(siteData.value.stadiumId)
  }
  if (templateId.value == null) {
    priceDatas.value = []
    convertListToReservations(priceDatas.value)
  } else {
    if (siteData.value.stadiumId && siteIdsString.value) {
      getReserveList(siteData.value.stadiumId, siteIdsString.value)
    }
  }
}

// 选择工作日节假日
const changeDateStatus = () => {
  if (siteData.value.stadiumId) {
    getBusinessTime(siteData.value.stadiumId)
  }
}

// 新增模版
const addTemplate = () => {
  handleStatus.value = 'add'
  if (isEditPrice.value) {
    saveTipsVisible.value = true
    return
  }
  addTempVisible.value = true
  tempForm.name = ''
  nextTick(() => {
    if (tempFormRef.value) {
      tempFormRef.value.resetFields()
    }
  })
}

// 删除模版
const handleDelTemp = () => {
  // this.$modal
  //   .confirm("是否确认删除该模版？")
  //   .then(async () => {
  if (templateId.value && templateList.value) {
    deleteTemplate(templateId.value).then((res) => {
      // this.$message.success(res.msg)
      templateList.value!.splice(templateIndex.value, 1)
      if (templateList.value && templateList.value.length > 0) {
        templateIndex.value = 0
        const firstTemplate = templateList.value[0]
        templateId.value = firstTemplate?.id || null
        templateName.value = firstTemplate?.templateName || ''
        dateStatus.value = firstTemplate?.templateType || ''
        disabledTimes.value = firstTemplate?.displayTimes?.split(',') || []
        isDefault.value = firstTemplate?.isDefault === 0 ? true : false
        if (siteData.value.stadiumId) {
          getBusinessTime(siteData.value.stadiumId)
          if (siteIdsString.value) {
            getReserveList(siteData.value.stadiumId, siteIdsString.value)
          }
        }
      }
    })
  } else if (templateList.value) {
    templateList.value.splice(templateIndex.value, 1)
  }
  //   })
  //   .catch(() => {})
}

// 保存模版
const handleSubmit = debounce(
  async (type?: number) => {
    if (!templateList.value) return

    const displayList = workTime.value
      .filter((item) => item.disabled)
      .map((ele) => {
        return ele.time
      })
    const params = {
      bulletinTemplateEntity: {
        stadiumId: siteData.value.stadiumId,
        templateName: templateName.value,
        id: templateId.value,
        templateType: dateStatus.value,
        siteType: siteType.value,
        isDefault: isDefault.value ? 0 : null,
      },
      bulletinTemplateDetailEntityList: priceDatas.value,
      displayList,
    }
    const res = await createBulletinTemplate(params)
    // this.$message.success("操作成功")
    await getTemplate(siteData.value.stadiumId, siteType.value)
    if (templateList.value && templateList.value[templateIndex.value]) {
      templateId.value = templateList.value[templateIndex.value]?.id || null
    }
    isEditPrice.value = false
    if (type == 1) {
      handleNotSave()
    }
  },
  1000,
  {
    leading: true,
    trailing: false,
  },
)

// 不保存模版切换其他模版
const handleNotSave = () => {
  isEditPrice.value = false
  saveTipsVisible.value = false
  saveDefaultVisible.value = false
  if (templateList.value && templateList.value[templateIndex.value]) {
    isDefault.value = templateList.value[templateIndex.value]?.isDefault == 0 ? true : false
  }
  if (handleStatus.value == 'cancel') {
    emit('cancel')
  } else if (handleStatus.value == 'add') {
    addTempVisible.value = true
  } else if (handleStatus.value == 'change') {
    templateId.value = templateParams.value.templateId
    templateIndex.value = templateParams.value.templateIndex
    templateName.value = templateParams.value.templateName
    if (siteData.value.stadiumId && siteIdsString.value) {
      getReserveList(siteData.value.stadiumId, siteIdsString.value)
    }
  }
}

// 取消
const handleCancel = () => {
  handleStatus.value = 'cancel'
  if (isEditPrice.value) {
    isDefault.value = false
    saveTipsVisible.value = true
    return
  }
  emit('cancel')
}

// 禁用时间
const handleDisabledTime = (item: WorkTimeItem) => {
  item.disabled = !item.disabled
}

// 设为默认
const handleDefault = () => {
  saveDefaultVisible.value = true
  isDefault.value = true
  handleStatus.value = ''
}

// 挂载时执行
getDaysDates()

// 暴露方法给父组件
defineExpose({
  open,
  handleCancel,
})
</script>

<style scoped lang="scss">
.dialog_header {
  position: sticky;
  top: 0;
  background: #fff;
  z-index: 9;
  .dialog_tit {
    display: flex;
    align-items: center;
    justify-content: space-between;
  }
  .dialog_close {
    padding: 5px;
    cursor: pointer;
  }
}
table {
  width: 100%;
  border-collapse: collapse;
  border-radius: 6px;
}

th,
td {
  border: 1px solid #e5e5e5;
  padding: 8px;
  div {
    line-height: 19px;
  }
}
.disabled_price {
  cursor: not-allowed;
}
th {
  background-color: #e5e5e5;
}
.dropdown-center {
  text-align: center;
}
.top_wrap {
  display: flex;
  border-bottom: 1px solid #e5e5e5;
  padding-bottom: 4px;
  padding-top: 20px;
  .template_list {
    display: flex;
    align-items: center;
    margin-left: 20px;
    .template_item {
      margin-right: 20px;
      height: 36px;
      line-height: 36px;
      padding: 0 18px;
      border: 1px solid #383838;
      background: rgba(56, 56, 56, 0.1);
      box-sizing: border-box;
      font-size: 14px;
      color: #383838;
      position: relative;
      border-radius: 6px;
      cursor: pointer;
      &.active {
        border-color: #0988fb;
        background: rgba(9, 136, 251, 0.1);
        color: #0988fb;
      }
      .temp_label {
        position: absolute;
        top: -10px;
        left: 0;
        width: 29px;
        height: 17px;
        line-height: 17px;
        z-index: 9;
        background: #2a82e4;
        font-size: 10px;
        color: #fff;
        border-radius: 6px;
        display: flex;
        align-items: center;
        justify-content: center;
      }
      :deep(.el-input__inner) {
        border: none;
        background: none;
        padding: 0;
      }
    }
    .add_box {
      img {
        width: 20px;
        height: 20px;
      }
    }
  }
  :deep(.el-select) {
    .el-input__inner {
      border-color: #383838;
      color: #383838;
    }
    .el-select__caret {
      color: #383838;
    }
  }
}
.temp_btn {
  text-align: center;
  position: absolute;
  bottom: 0;
  z-index: 9;
  background: #fff;
  width: 100%;
  left: 0;
  padding-bottom: 34px;
  padding-top: 10px;
}
.el-button {
  width: 90px;
  height: 38px;
  line-height: 38px;
  border-radius: 8px;
  padding: 0;
  font-size: 16px;
  &.el-button--default {
    background: #e5e5e5;
    border: none;
    color: #808080;
  }
  & + .el-button {
    margin-left: 40px;
  }
}
:deep(.add_temp) {
  display: flex;
  flex-direction: column;
  margin: 0 !important;
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.not_set {
  display: flex;
  justify-content: center;
  align-items: center;
  padding-top: 281px;
  img {
    width: 48px;
    height: 50px;
    margin-right: 18px;
  }
  .p1 {
    font-size: 16px;
    color: #a6a6a6;
    line-height: 24px;
  }
  .p2 {
    font-size: 16px;
    color: #0988fb;
    line-height: 24px;
    cursor: pointer;
  }
}
</style>
